import { ref, reactive, computed } from 'vue';
import { MessageRecord } from '@/api/aiChatPage/types';
import { ChatSource, MessageType } from '@/enums/MessageEnum';
import { addAnswer, chatCancel, chatLaunch, chatMessageList, chatRetrieve, conversationCreate, conversationMessageList, streamChat } from '@/api/aiChatPage';
import { AbortablePromise } from '@/utils/http/types';
import { nextTick } from 'vue';

export interface ChatOptions {
    uuid: string,
    circleUuid: string | '',
    circleName: string | '',
    chatSource: ChatSource,
}
/**
 * 聊天功能Hook，每个聊天框使用独立实例
 */
export function useChat(op: ChatOptions) {
    // 聊天状态
    const messageList = ref<Array<MessageRecord & { pageNum?: number }>>([]);
    const conversationId = ref('');
    const uuid = ref(op.uuid); // 机器人ID
    const inputContent = ref('');
    const currentStream = ref<null | AbortablePromise<any>>(null);
    const current = ref(0); // 当前页码
    const size = ref(20);   // 每页数量
    const hasMore = ref(true); // 是否有更多历史记录
    const isLoadingMore = ref(false);
    const circleUuid = ref(op.circleUuid);
    const circleName = ref(op.circleName);
    const chatSource = ref(op.chatSource);

    // 全局共享配置
    const loadingText = '正在思考...';
    const headerHeight = ref(0);
    const footerHeight = ref(uni.upx2px(136));
    const windowHeight = uni.getSystemInfoSync().windowHeight;

    // 计算属性
    const lastMessage = computed(() => {
        const items = messageList.value.filter(item => item.type === MessageType.ANSWER);
        return items.length ? items[0] : {} as MessageRecord;
    });



    // 创建消息
    const createMessage = (type: MessageType, content: string, options: Partial<MessageRecord> = {}): MessageRecord => {
        return {
            type,
            content,
            loading: false,
            typing: false,
            ...options
        } as MessageRecord;
    };

    // 创建并添加消息
    const createAndAddMessage = (type: MessageType, content: string, options = {}) => {
        const message = createMessage(type, content, options);
        messageList.value.unshift(message);
        return message;
    };

    // 设置最后一条消息
    const setLastMessage = (value: MessageRecord) => {
        console.log('setLastMessage', value);
        const lastMsg = messageList.value[0];
        if (!lastMsg) return;

        lastMsg.typing = value.typing;
        lastMsg.loading = value.loading;
        if (lastMsg.content.includes(loadingText)) {
            lastMsg.content = lastMsg.content.replace(loadingText, '') + value.content;
        } else {
            lastMsg.content = lastMsg.content + value.content;
        }
    };

    // 发送消息
    const handleMessageSend = async (content: string) => {
        // 重置输入框
        inputContent.value = '';
        const trimmedContent = content.trim();
        if (!trimmedContent) return;

        try {
            createAndAddMessage(MessageType.QUESTION, trimmedContent);
            createAndAddMessage(MessageType.ANSWER, loadingText, {
                typing: true,
                loading: true
            });

            const stream = streamChat({
                conversationId: conversationId.value,
                uuid: uuid.value,
                contentType: 'text',
                content: trimmedContent,
                chatSource: chatSource.value as ChatSource,
                circleUuid: circleUuid.value
            });

            // 拼接流式数据
            stream.onChunk((chunk) => {
                setLastMessage({
                    content: chunk,
                    typing: true,
                    loading: false,
                });
            });

            // 流式数据结束
            stream.onComplete(() => {
                nextTick(() => {
                    setLastMessage({
                        content: '',
                        typing: false,
                        loading: false,
                    });

                    currentStream.value = null;
                    addAnswer({
                        conversationId: conversationId.value,
                        content: lastMessage.value.content,
                        uuid: uuid.value,
                        contentType: 'text',
                    });
                });
            });

            stream.onError((error) => {
                setLastMessage({
                    content: '发送错误',
                    typing: false,
                    loading: false,
                });
            });

            // 取消流式请求
            stream.onCancel(async () => {
                // 取消服务端的请求
                await chatCancel({
                    conversationId: conversationId.value,
                });
                setLastMessage({
                    content: '',
                    typing: false,
                    loading: false,
                });
            });

            // 启动流并保存引用
            currentStream.value = stream.start();
        } catch (error: any) {
            setLastMessage({
                content: '抱歉，处理您的消息时出现了问题',
                typing: false,
                loading: false,
            });
        }
    };

    // 重发消息
    const handleResend = async () => {
        const lastQuestion = messageList.value.find(item => item.type === MessageType.QUESTION);
        if (lastQuestion) {
            handleMessageSend(lastQuestion.content);
        }
    };

    // 取消当前查询
    const cancelCurrentQuery = async () => {
        if (currentStream.value) {
            currentStream.value.abort();
            currentStream.value = null;
        }
    };

    // 初始化聊天
    const initChat = async (botUuid: string) => {
        try {
            uuid.value = botUuid;
            // 创建会话
            const createRes = await conversationCreate(uuid.value);
            conversationId.value = createRes.id;
            // 查询最新消息
            await loadMessages();
        } catch (error) {
            uni.showToast({
                title: '初始化对话失败',
                icon: 'none',
            });
        }
    };

    // 复制消息
    const copyMessage = (content: string) => {
        uni.setClipboardData({
            data: content,
            success: () => {
                uni.showToast({
                    title: '已复制',
                    icon: 'none',
                });
            },
        });
    };

    // 设置输入内容
    const setInputContent = (content: string) => {
        inputContent.value = content;
    };

    // 更新底部高度
    const updateFooterHeight = (height: number) => {
        footerHeight.value = height;
    };

    // 加载消息
    const loadMessages = async () => {
        isLoadingMore.value = true;
        try {
            const requestPage = current.value + 1;
            const res = await conversationMessageList({
                conversationId: conversationId.value,
                current: requestPage,
                size: size.value
            });
            hasMore.value = requestPage * size.value <= res.total;

            if (requestPage === 1) {
                console.log(res.records);
                messageList.value = res.records;
            } else {
                messageList.value.push(...res.records);
            }

            current.value = requestPage;
        } catch (error) {
            uni.showToast({
                title: '加载消息失败',
                icon: 'none'
            });
        } finally {
            isLoadingMore.value = false;
        }
    };

    // 加载更多消息
    const loadMoreMessages = async () => {
        if (hasMore.value && !isLoadingMore.value) {
            await loadMessages();
        }
    };

    // 设置聊天来源
    const setChatSource = (source: ChatSource) => {
        chatSource.value = source;
    };

    // 设置圈子信息
    const setCircleInfo = (uuid: string, name: string) => {
        circleUuid.value = uuid;
        circleName.value = name;
    };

    return {
        // 状态
        messageList,
        conversationId,
        uuid,
        inputContent,
        headerHeight,
        footerHeight,
        windowHeight,
        current,
        hasMore,
        isLoadingMore,
        loadingText,
        circleUuid,
        circleName,
        chatSource,
        lastMessage,

        // 方法
        initChat,
        handleMessageSend,
        handleResend,
        cancelCurrentQuery,
        copyMessage,
        setInputContent,
        updateFooterHeight,
        loadMessages,
        loadMoreMessages,
        setChatSource,
        setCircleInfo,
        createAndAddMessage,
    };
}